<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="RoleList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbuttom',i1===0?'bdtop':'','vcenter']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <el-col :span="5">
                <el-tag closable @close="removeByRightsId(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  :class="['bdbuttom',i2===0?'':'bdtop','vcenter']"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeByRightsId(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeByRightsId(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>
              {{scope.row.children}}
            </pre>-->
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id,scope.row.roleName)"
            ></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRightDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%" @close="addCloseHandle">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCloseHandle">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="50%" @close="editCloseHandle">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCloseHandle">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="closeSetRightDialog"
    >
      <div :class="'el-dialog-div'">
        <el-tree
          :data="RightsList"
          :props="treeProps"
          node-key="id"
          show-checkbox
          default-expand-all
          :default-checked-keys="defaultKey"
          ref="treeRef"
        ></el-tree>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRightsList">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      RoleList: [],
      RightsList: [],
      addForm: {
        roleName: "",
        roleDesc: ""
      },
      editForm: {},
      addDialogVisible: false,
      editDialogVisible: false,
      setRightDialogVisible: false,
      addFormRules: {
        roleName: { required: true, message: "请输入角色名称", trigger: "blur" }
      },
      editFormRules: {
        roleName: { required: true, message: "请输入角色名称", trigger: "blur" }
      },
      treeProps: {
        label: "authName",
        children: "children"
      },
      defaultKey: [],
      roleId: ""
    };
  },
  created() {
    this.getRoleList();
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      } else {
        // console.log(res.data);
        this.RoleList = res.data;
      }
    },
    addRoles() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error("表单内容格式不正确");
        } else {
          const { data: res } = await this.$http.post("/roles", this.addForm);
          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg);
          } else {
            this.$message.success(res.meta.msg);
            this.addDialogVisible = false;
            this.getRoleList();
          }
        }
      });
    },
    addCloseHandle() {
      this.addDialogVisible = false;
      this.$refs.addFormRef.resetFields();
      this.getRoleList();
    },
    async showEditDialog(id) {
      const { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      } else {
        this.editDialogVisible = true;
        this.editForm = res.data;
      }
    },
    editCloseHandle() {
      this.editDialogVisible = false;
      this.$refs.editFormRef.resetFields();
      this.getRoleList();
    },
    editRoles() {
      console.log(this.editForm);
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error("表单格式不正确！");
        } else {
          const { data: res } = await this.$http.put(
            "roles/" + this.editForm.roleId,
            {
              roleName: this.editForm.roleName,
              roleDesc: this.editForm.roleDesc
            }
          );
          console.log(res);
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg);
          } else {
            this.$message.success(res.meta.msg);
            this.editCloseHandle();
          }
        }
      });
    },
    async deleteUser(roleId, roleName) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      // console.log(confirmResult);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      } else {
        const { data: res } = await this.$http.delete("roles/" + roleId);
        console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg + "删除失败");
        } else {
          this.$message.success("角色" + roleName + "已被删除成功!");
          this.getRoleList();
        }
      }
    },
    async removeByRightsId(role, rightId) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该角色权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      } else {
        const { data: res } = await this.$http.delete(
          `roles/${role.id}/rights/${rightId}`
        );
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg);
        } else {
          this.$message.success(res.meta.msg);
          // this.getRoleList();
          role.children = res.data;
        }
      }
    },
    async showSetRightDialog(role) {
      this.roleId = role.id;
      const { data: res } = await this.$http.get("rights/tree");

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg + ",获取数据失败！");
      } else {
        this.RightsList = res.data;
        // console.log(this.RightsList);
        this.getLeafKeys(role, this.defaultKey);
        this.setRightDialogVisible = true;
      }
    },
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      } else {
        node.children.forEach(item => this.getLeafKeys(item, arr));
      }
    },
    closeSetRightDialog() {
      this.defaultKey = [];
    },
    async addRightsList() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      const idStr = keys.join(",");

      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: idStr
        }
      );
      console.log(idStr);
      console.log(res.meta);

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg + "，分配权限失败！");
      } else {
        this.$message.success(res.meta.msg + "，权限分配成功！");
        this.setRightDialogVisible = false;
        this.getRoleList();
      }
    }
  }
};
</script>
<style lang="less">
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}
.bdbuttom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}

.el-dialog-div {
  height: 60vh;
  overflow: auto;
}
</style>